const UploadFactory = (() => {
    let createdFlyWeightObjs = {};

    return {
        create(uploadType) {
            if (createdFlyWeightObjs[uploadType]) {
                return createdFlyWeightObjs[uploadType];
            }

            return createdFlyWeightObjs[uploadType] = new Upload(uploadType);
        }
    }
})();

const uploadManager = (() => {
    let uploadDatabase = {};

    return {
        add(id, uploadType, fileName, fileSize) {
            let flyWeightObj = UploadFactory.create(uploadType);

            let dom = document.createElement('div');
            dom.innerHTML = `
                <span>文件名称:${fileName}, 文件大小:${fileSize}</span>
                <button class="delFile">删除</button>`
            dom.querySelector('.delFile').onclick = () => {
                flyWeightObj.delFile(id);
            }
            document.body.appendChild(dom);

            uploadDatabase[id] = {
                fileName,
                fileSize,
                dom
            }

            return flyWeightObj;
        },
        setExternalState(id, flyWeightObj) {
            let uploadData = uploadDatabase[id];
            Object.assign(flyWeightObj, uploadData);
        }
    }
})();

class Upload {
    constructor(uploadType) {
        this.uploadType = uploadType;
    }

    delFile(id) {
        uploadManager.setExternalState(id, this);

        if (this.fileSize < 3000) {
            return this.dom.parentNode.removeChild(this.dom);
        }
        if (window.confirm(`确定要删除该文件吗? ${this.fileName}`)) {
            return this.dom.parentNode.removeChild(this.dom);
        }
    }
}

let id = 0;

/**
 * @param {string} uploadType 区分是控件还是 flash
 * @param {array} files 
 */
window.startUpload = (uploadType, files) => {
    for (let file of files) {
        let uploadObj = uploadManager.add(++id, uploadType, file.fileName, file.fileSize);
    }
};
